/*
 * Copyright (c) 2011 Ball State University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * NOTE:
 * Derivative work based on the Google IO 2011 Schedule app released for open source
 * http://code.google.com/p/iosched/
 */

package edu.bsu.android.gtv.apps.bconnected.ui; 

import java.util.ArrayList;

import edu.bsu.android.gtv.apps.bconnected.data.ConnectionData;
import edu.bsu.android.gtv.apps.bconnected.R;
import edu.bsu.android.gtv.apps.bconnected.data.CourseData;
import edu.bsu.android.gtv.apps.bconnected.data.PersonData;
import edu.bsu.android.gtv.apps.bconnected.objects.Course;
import edu.bsu.android.gtv.apps.bconnected.objects.Person;
import edu.bsu.android.gtv.apps.bconnected.ui.base.BaseActivity;
import edu.bsu.android.gtv.apps.bconnected.util.Adapters;
import edu.bsu.android.gtv.apps.bconnected.util.AnalyticsUtils;
import edu.bsu.android.gtv.apps.bconnected.util.Constants;
import edu.bsu.android.gtv.apps.bconnected.util.FractionalTouchDelegate;
import edu.bsu.android.gtv.apps.bconnected.util.LoginHelper;
import edu.bsu.android.gtv.apps.bconnected.util.UIUtils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.RectF;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

/**
 * An activity that shows the course instructor information. Activity that is started when a user selects an 
 * instructor from the list on the {@link CourseInfoActivity}.
 * @author Kyle Parker, University Computing Services
 */
public class InstructorInfoActivity extends BaseActivity {   
    private static final String TAG = "InstructorInfoActivity";
    private static final String TAG_OTHER_COURSES = "other";  
    
    private TabHost mTabHost;
    private View mLoadingSpinner;
    private View mOtherCoursesSpinner;
    private Activity mActivity;
    private BroadcastReceiver mReceiver;
    private CompoundButton mStarred;

    private String mBSUID;
    private String mLoginGuid;
    private String mPersonBSUID;
    private String mBuildingDesc;
    private String mLatitude;
    private String mLongitude;
    private Person mInstructor;
    private String mTermNumber;
    private String mTermYear;
    private boolean mLogin;
    
    private int mInstructorPosition = 0;
    private int mCoursePosition = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_instructor_info);
		
        getActivityHelper().setupActionBar(false, "Course Schedule | Instructor");        
        mActivity = this;
        
        handleLogout();    
        handleLogin();
                
        mTabHost = (TabHost) findViewById(android.R.id.tabhost);
       	mTabHost.setup();

        mLoadingSpinner = findViewById(R.id.loading_spinner); 
        mLoadingSpinner.setVisibility(View.VISIBLE);	
        
        mOtherCoursesSpinner = findViewById(R.id.spinner_other_courses); 
        mOtherCoursesSpinner.setVisibility(View.VISIBLE);
        
        mStarred = (CompoundButton) findViewById(R.id.star_button);
        mStarred.setFocusable(true);
        mStarred.setClickable(true);
        
        // Larger target triggers star toggle
        final View starParent = findViewById(R.id.name);
        FractionalTouchDelegate.setupDelegate(starParent, mStarred, new RectF(0.6f, 0f, 1f, 0.8f));

        setupOtherCoursesTab(); 
        getExtras();

		// Hide the instructor while the data is loading
        hideInstructorInfo();
		if (mLogin) {
			loadInstructorInfo();
		}

        AnalyticsUtils.getInstance(mActivity).trackPageView("/Instructor");
    }
    
    @Override 
    public void onDestroy() {
    	super.onResume();
    	mActivity.unregisterReceiver(mReceiver);
    }
    
    /**
     * Get the extras from the Intent
     */
    public void getExtras() {
		Bundle extras = getIntent().getExtras(); 

		if (extras != null) {
			if (extras.getString(Constants.EXTRA_INSTRUCTOR_POSITION) != null) {
				mInstructorPosition = Integer.parseInt(extras.getString(Constants.EXTRA_INSTRUCTOR_POSITION));
			}
			if (extras.getString(Constants.EXTRA_COURSE_POSITION) != null) {
				mCoursePosition = Integer.parseInt(extras.getString(Constants.EXTRA_COURSE_POSITION));
			}
		}
    }

    /**
     * Using a new thread, separate from the main activity, load the instructor information from the service handler
     */
    private void loadInstructorInfo() {
        Runnable load = new Runnable(){
            public void run() {
            	try {
	            	if (CourseData.getCourseCount() > 0) {
	        	    	String crn = CourseData.getCourse(mCoursePosition).getCourseRefNum();
	        	        mTermNumber = CourseData.getCourse(mCoursePosition).getTermNumber();
	        	        mTermYear = CourseData.getCourse(mCoursePosition).getTermYear();
	        	        
	        	        PersonData.initializeInstructor(mBSUID, crn, mTermNumber, mTermYear, mActivity);
	                	mInstructor = PersonData.getInstructor(mInstructorPosition);
	                	mPersonBSUID = mInstructor.getBSUID();	                	                 
	            	}
	    	    	
	        		mActivity.runOnUiThread(returnInstructor);
            	} catch (Exception ex) {
                    AnalyticsUtils.getInstance(mActivity).trackPageView(TAG + ": " + ex.getMessage());
            	}
            }
        };
        
        Thread thread = new Thread(null, load, "loadInstructor");
        thread.start();
    }
    
    /**
     * Load the instructor info from the service handler and set the visibility of the spinner to "gone"
     */
    private Runnable returnInstructor = new Runnable(){
        public void run() {
        	displayInstructor();
            mLoadingSpinner.setVisibility(View.GONE);
        }
    };

    /**
     * Using a new thread, separate from the main activity, load the other course taught by the instructor from the service handler
     */
    private void loadOtherCourse() {			
        Runnable load = new Runnable(){
            public void run() { 
            	try {
            		CourseData.initializeOtherCourses(mPersonBSUID, mActivity);
        	    	
            		mActivity.runOnUiThread(returnOtherCourse);   
            	} catch (Exception ex) {
                    AnalyticsUtils.getInstance(mActivity).trackPageView(TAG + ": " + ex.getMessage());
            	}
            }
        };
        
        Thread thread = new Thread(null, load, "loadOtherCourse");
        thread.start();
    }
    
    /**
     * Display the other course taught by the instructor in a separate thread
     */
    private Runnable returnOtherCourse = new Runnable(){
        public void run() {
            displayOtherCourses(CourseData.getOtherCourses());
            mOtherCoursesSpinner.setVisibility(View.GONE);
            
            if (CourseData.getOtherCoursesCount() == 0) {
                TextView empty = ((TextView) findViewById(R.id.empty_other_courses));
                empty.setVisibility(View.VISIBLE);
            }
        }
    };
    
    /**
     * Display the instructor information, set the starred status and show the other courses taught
     */
    private void displayInstructor() {
        if (mInstructor != null) { 
        	LinearLayout view = (LinearLayout) findViewById(R.id.instructor_info_container);
            view.setVisibility(View.VISIBLE);
        	view.setBackgroundResource(R.color.content_background);
            
            loadOtherCourse();            
    		String name = (mInstructor.getNamePrefix() + " " + mInstructor.getFirstName() + " " + mInstructor.getLastName() + " " + 
    				mInstructor.getNameSuffix()).trim();
    		
    		mBuildingDesc = mInstructor.getBuildingDesc();
    		mLongitude = mInstructor.getLongitude();
    		mLatitude = mInstructor.getLatitude();
        		
    		UIUtils.displayTextView(view, R.id.name, name);
    		UIUtils.displayTextView(view, R.id.email, mInstructor.getEmailAddress());
    		UIUtils.displayTextView(view, R.id.phone, mInstructor.getPhone());
    		UIUtils.displayTextView(view, R.id.title, mInstructor.getTitleRank());
    		UIUtils.displayTextView(view, R.id.department, mInstructor.getDepartment());
    		UIUtils.displayTextView(view, R.id.office, mInstructor.getBuildingCode() + " " + mInstructor.getRoom());
	        
            // Unregister around setting checked state to avoid triggering listener since change isn't user generated.
            mStarred.setOnCheckedChangeListener(null);
            mStarred.setChecked(mInstructor.getStarred());
            mStarred.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			    	ConnectionData.insertConnection(mBSUID, mLoginGuid, mPersonBSUID, Constants.VALUE_PERSON_TYPE_FACULTY, 
			    			isChecked, mActivity);
			    }           	
            });
    	} else {  
    		hideInstructorInfo();
    		((TextView) showEmptyInstructorInfo().findViewById(R.id.empty_instructor_info)).setText(R.string.empty_instructor_info);
    	}
    }

    /** 
     * Hide the instructor view during the load process or if the instructor object is empty
     */
	private void hideInstructorInfo() { 
		LinearLayout view = (LinearLayout) findViewById(R.id.instructor_info_container);
        view.setVisibility(View.GONE);			
	}

    /**
     * Show the instructor view during the load process or if the instructor object is empty
     */
	private View showEmptyInstructorInfo() {
		LinearLayout view = (LinearLayout) findViewById(R.id.empty_instructor_info_container);
		view.setVisibility(View.VISIBLE);
        view.setBackgroundResource(R.drawable.empty_schedule);
        
        return view;
	}
    
    /**
     * Display the other courses that the instructor teaches
     * @param ArrayList<Course> otherCourses
     */
    private void displayOtherCourses(ArrayList<Course> otherCourses) { 		
    	Adapters.CourseAdapter adapter = new Adapters.CourseAdapter(mActivity, otherCourses, Constants.TARGET_OTHER_COURSE);

        final ListView lv = ((ListView) findViewById(R.id.other_courses));
        lv.setAdapter(adapter);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = new MenuInflater(this);
    	inflater.inflate(R.menu.map_menu_items, menu);
    	
    	super.onCreateOptionsMenu(menu);
        
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_map:
            	Intent intent = UIUtils.getGoogleMapsIntent(mBuildingDesc, mLatitude, mLongitude);
            	
            	if (intent != null) {
            		startActivity(intent);
            	} else {
                    final String errorText = mActivity.getString(R.string.toast_error_location); 
                    Toast.makeText(mActivity, errorText, Toast.LENGTH_LONG).show();
            	}
                return true;
        }
        
        return super.onOptionsItemSelected(item);
    }
    
    /**
     * Build and add "other courses" tab.
     */
    private void setupOtherCoursesTab() {
        mTabHost.addTab(mTabHost.newTabSpec(TAG_OTHER_COURSES)
                .setIndicator(UIUtils.buildIndicator(R.string.tab_instructor_other_courses, mActivity))
                .setContent(R.id.tab_other_course));
    }

    /**
     * In order to protect the activity from the back stack after a student logs out, remove the activity 
     * If the student hits the back button, this will take them to the Home activity
     */
    private void handleLogout() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION_LOGOUT);
        mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
			    Log.d("onReceive","Logout in progress");
		        intent = new Intent(Intent.ACTION_VIEW, null, mActivity, HomeActivity.class);
		        intent.putExtra(Constants.EXTRA_LOGIN_STATUS, Integer.toString(Constants.LOGIN_STATUS_LOGOUT));
		        
		        mActivity.startActivity(intent); 
			    mActivity.finish();
			}
		};
		
        mActivity.registerReceiver(mReceiver, intentFilter);
    }
    
    /**
     * Determine if the person has logged in and whether there is a person object in the database
     * Get the student's BSU ID for use throughout the application
     */
    private void handleLogin() {
    	Person person = LoginHelper.checkLogin(mActivity);
    	
    	if (person != null) {
    		mBSUID = person.getBSUID();
        	mLoginGuid = person.getLoginGuid();
        	mLogin = true;
    	} else {
	        Intent intent = new Intent(Intent.ACTION_VIEW, null, mActivity, HomeActivity.class);
	        intent.putExtra(Constants.EXTRA_LOGIN_STATUS, Integer.toString(Constants.LOGIN_STATUS_NOT_LOGGED_IN));
	        
	        mActivity.startActivity(intent); 
		    mActivity.finish();
		    
		    mLogin = false;
    	}    	
    }
}
